import React from 'react';
import {
  View,
  TouchableOpacity,
  Text,
  Image,
  ListView,
  ScrollView,
  Alert,
} from 'react-native';

import BasePage from '../common/BasePage';
import TImage from '../../components/TImage';
import SizeUtils from '../../common/SizeUtils';
import Config from '../../config';
import JifenMallAwardAction from '../../actions/jifenmall/JifenMallAwardAction';
import JifenMallChoujiangAction from '../../actions/jifenmall/JifenMallChoujiangAction';
import JifenMallGetLuckerListAction from '../../actions/jifenmall/JifenMallGetLuckerListAction';
import BaseItem from '../common/BaseItem';
import ToastUtils from '../../common/ToastUtils';
import CommonDataListView from '../common/CommonDataListView';

//award 协议
export default class JifenLuckDrawPage extends BasePage {
  constructor(props) {
    super(props);
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

    this.state.awardData = null;
    this.state.curBtnIndex = -1;
    this.state.dataSource = ds.cloneWithRows([]);
    this.state.luckData = null; //抽奖返回信息
    this.state.statusText = "";

    this.selectedItemCount = 0;
    this.interval = null;
    this._btnDisable = false;

    this.awardIdData = {};

    this._imgBgWidth = SizeUtils.getWindowSize().width;
    this._imgBgHeight = SizeUtils.getWindowSize().width / 750 * 536;

    this._choujiangBtnWidth = SizeUtils.translateDesignWidthToCode(210);
    this._choujiangBtnHeight = SizeUtils.translateDesignWidthToCode(166);

    this._cellListTop = SizeUtils.translateDesignHeightToCode(350);
    this._cellWidth = SizeUtils.translateDesignWidthToCode(182);
    this._cellHeight = SizeUtils.translateDesignWidthToCode(164);
    this._cellGapWidth = SizeUtils.translateDesignWidthToCode(12);
    this._cellGapHeight = SizeUtils.translateDesignWidthToCode(12);

    this._awardImageWidth = SizeUtils.translateDesignWidthToCode(100);
    this._awardImageHeight = SizeUtils.translateDesignWidthToCode(100);

    this._midBgHeight = this._cellWidth * 3 + this._cellGapWidth * 2 + SizeUtils.translateDesignHeightToCode(70);

    this._backgroudColor = "#ffffff00";
  }

  componentWillUpdate(nextProps, nextState) {
    super.componentWillUpdate(nextProps, nextState);
    if(nextState.statusText != "") {
      ToastUtils.show(nextState.statusText);
      nextState.statusText = "";
    }
  }
  _onRenderHeader() {
    return (
      <View style={{width:SizeUtils.getWindowSize().width,
        height:this._cellListTop + SizeUtils.translateDesignHeightToCode(40)+this._midBgHeight}}>
        {this._renderBg()}
        <Image resizeMode={'stretch'} style={{width:this._midBgHeight+ SizeUtils.translateDesignWidthToCode(30),
            height:this._midBgHeight,
            left:(SizeUtils.getWindowSize().width - this._midBgHeight-SizeUtils.translateDesignWidthToCode(30))/2,
            position:"absolute",
            top:this._cellListTop - SizeUtils.translateDesignHeightToCode(15),
          }} source={require("../../../resource/images/jifenmall/awardbg.png")} />
          {this._renderAwardItems()}
          {this._renderChoujiangBtn()}
          {this._renderNoticeTxt()}
      </View>
    )
  }
  _dealRender(){
    return(
      <View style={{backgroundColor:"#5377fb", width:SizeUtils.getWindowSize().width,}}>
          
          {this._renderLuckerList()}
        {/* </ScrollView> */}
        {this._renderNavigationBar()}
      </View>
    )
  }

  componentDidMount() {
    this._requestPoint();
  }

  _requestPoint(){
    new JifenMallAwardAction().call(this, {});
  }

  _renderBg(){
    return(
      <View style={{flexDirection:"column", alignItems: 'center'}}>
        <TImage source={require("../../../resource/images/jifenmall/choujiang_img_bg2.png")}
            style={{width:this._imgBgWidth, height:this._imgBgHeight}} translatedSize={true}/>
        <View style={{position:"absolute", top:SizeUtils.translateDesignHeightToCode(100)}}>
          <TImage source={require("../../../resource/images/jifenmall/choujiang_img_tittle.png")}
              style={{width:469, height:179}}/>
        </View>
        <TImage resizeMode={'contain'} source={require("../../../resource/images/jifenmall/jfbg.png")}
              style={{position:"absolute",width:260, height:120,
              top:SizeUtils.translateDesignHeightToCode(100) + SizeUtils.translateDesignWidthToCode(115)}}/>
        <View style={{position:"absolute",flexDirection:"row",width:SizeUtils.translateDesignWidthToCode(200),
            height:SizeUtils.translateDesignHeightToCode(120), alignItems: 'center', justifyContent: 'center', backgroundColor:"#00000000",
            top:SizeUtils.translateDesignHeightToCode(100) + SizeUtils.translateDesignWidthToCode(115)}}>
          <Text style={{backgroundColor:"#00000000",color:'#fff',marginTop:-1, fontSize:SizeUtils.translateFontSizeToCode(26)}}>
            {'我的积分:'+this._getPoint()}
          </Text>
        </View>
      </View>
    )
  }

  _getPoint(){
    if(this.state.awardData != null && this.state.awardData.point != undefined)
    {
      return this.state.awardData.point.points;
    }
  }

  _renderAwardItems(){
    if(this.state.awardData != null && this.state.awardData.links != undefined)
    {
      let cellsWidth = this._cellWidth * 3 + this._cellGapWidth * 2;
      return(
        <View style={{width:SizeUtils.getWindowSize().width, backgroundColor:"#ff6464",
          height:this._cellHeight * 3 + this._cellGapHeight * 2, backgroundColor:"#00000000",
          position:"absolute", top:this._cellListTop+SizeUtils.translateDesignHeightToCode(30), flexDirection:"column", alignItems:"center",
          justifyContent:"space-between"}}>
            <View style={{flexDirection:"row", justifyContent:"space-between",
                width:cellsWidth}}>
              {this._getItemLine0Arr().map(
                (data, index) => {
                    return this._renderAwardItem(data.data, data.index);
                }
              )}
            </View>

            <View style={{flexDirection:"row" , justifyContent:"space-between",
                width:cellsWidth}}>
              {this._getItemLine1Arr().map(
                (data, index) => {
                    return this._renderAwardItem(data.data, data.index);
                }
              )}
            </View>
            <View style={{flexDirection:"row",  justifyContent:"space-between",
                width:cellsWidth}}>
              {this._getItemLine2Arr().map(
                (data, index) => {
                    return this._renderAwardItem(data.data, data.index);
                }
              )}
            </View>
        </View>
      )
    }
  }

  _getItemLine0Arr(){
    var arr = [];
    if(this.state.awardData && this.state.awardData.links != undefined)
    {
      arr = [
        {data:this.state.awardData.links.awards[0], index:0},
        {data:this.state.awardData.links.awards[1], index:1},
        {data:this.state.awardData.links.awards[2], index:2},
      ];
      this.awardIdData[this.state.awardData.links.awards[0].award_id] = 0;
      this.awardIdData[this.state.awardData.links.awards[1].award_id] = 1;
      this.awardIdData[this.state.awardData.links.awards[2].award_id] = 2;
    }
    return arr;
  }

  _getItemLine1Arr(){
    var arr = [];
    if(this.state.awardData && this.state.awardData.links != undefined)
    {
      arr = [
        {data:this.state.awardData.links.awards[7], index:7},
        {data:this.state.awardData.links.awards[3], index:3},
      ];
      this.awardIdData[this.state.awardData.links.awards[7].award_id] = 7;
      this.awardIdData[this.state.awardData.links.awards[3].award_id] = 3;
    }
    return arr;
  }

  _getItemLine2Arr(){
    var arr = [];
    if(this.state.awardData && this.state.awardData.links != undefined)
    {
      arr = [
        {data:this.state.awardData.links.awards[6], index:6},
        {data:this.state.awardData.links.awards[5], index:5},
        {data:this.state.awardData.links.awards[4], index:4},
      ];
      this.awardIdData[this.state.awardData.links.awards[6].award_id] = 6;
      this.awardIdData[this.state.awardData.links.awards[5].award_id] = 5;
      this.awardIdData[this.state.awardData.links.awards[4].award_id] = 4;
    }
    return arr;
  }

  _renderAwardItem(data, index){
    let awardItemTop = (this._cellHeight - this._awardImageHeight)/2;
    return(
      <View key={index} style={{flexDirection:"column", alignItems:"center",
        width:this._cellWidth, height:this._cellHeight}}>
        <TImage resizeMode={'contain'} source={require("../../../resource/images/jifenmall/choujiang_btn_n.png")}
            style={{width:this._cellWidth, height:this._cellHeight,}} translatedSize={true}/>
        {this._renderSelectedItemImg(index)}
        <View style={{
          position:"absolute",
          top:awardItemTop,
          left:(this._cellWidth - this._awardImageWidth)/2}}>
          <TImage resizeMode={'contain'} source={this._getItemImgURL(data)}
            style={{width:this._awardImageWidth, height:this._awardImageHeight,
            }} isMini={true}
            translatedSize={true}/>
        </View>
        {/* <Text style={{position:"absolute", top:awardItemTop + SizeUtils.translateDesignHeightToCode(10) + this._awardImageHeight,
            color:"#999999", backgroundColor:"#00000000"}}>
          {data.name} * {data.num}</Text> */}
        {/* <Text style={{bottom:SizeUtils.translateDesignHeightToCode(324)}}>
          {this._getSelectedBtnTxt(index, this.state.curBtnIndex)}</Text> */}
      </View>
    )
  }

  _getSelectedBtnTxt(index, curIndex){
    if(index == curIndex)
    {
      return "是我啊";
    }
  }

  _renderSelectedItemImg(index){
    return(
      <View style={{position:"absolute", top:0, left:index === this.state.curBtnIndex ? 0 : -9999}}>
        <TImage resizeMode={'contain'} source={require("../../../resource/images/jifenmall/choujiang_btn_h.png")}
            style={{width:this._cellWidth, height:this._cellHeight}} translatedSize={true}/>
      </View>
    )
  }

  _getItemImgURL(data){
    if(data !=null && data.image_url != undefined) {
      return {uri:data.image_url};
    }
    else {
      return require("../../../resource/images/jifenmall/mall_icon_choujiang.png");
    }
  }

  _renderChoujiangBtn(){
    return(
      <View style={{width:SizeUtils.getWindowSize().width, position:"absolute", flexDirection:"row",
          justifyContent:"center"}}>
          <TouchableOpacity onPress={this._onChoujiang.bind(this)}
            style={{position:"absolute",
              top:this._cellListTop + this._midBgHeight/2 - this._choujiangBtnHeight/2 - SizeUtils.translateDesignHeightToCode(30)}}>
              <TImage resizeMode={'contain'} source={require("../../../resource/images/jifenmall/choujiang_btn_click.png")}
                  style={{width:this._choujiangBtnWidth, height:this._choujiangBtnHeight,}} translatedSize={true}/>

          </TouchableOpacity>
      </View>
    )
  }
  /*

  <Text style={{fontSize:SizeUtils.translateFontSizeToCode(22),
    width:SizeUtils.translateDesignWidthToCode(120),
    bottom:SizeUtils.translateDesignWidthToCode(145),textAlign:"center", backgroundColor:"#ff000000",
    color:"#ffffff", left:SizeUtils.translateDesignWidthToCode(112),}}>
    剩余{this.getLeftTime()}次
  </Text>
  */
  getLeftTime(){
    let leftTime = 0;
    if(this.state.awardData != null && this.state.awardData.left_times != undefined)
    {
      leftTime = this.state.awardData.left_times;
    }
    if(leftTime == -1)
    {
      leftTime = "无限";
    }
    return leftTime;
  }

  //获取每次抽奖需要的积分
  getCost(){
    var cost = 0;
    if(this.state.awardData && this.state.awardData.cost != undefined)
    {
      cost = this.state.awardData.cost;
    }
    return cost;
  }

  _onChoujiang(){
    if(this.state.awardData && this.state.awardData.left_times != undefined)
    {
      if(this.state.awardData.left_times == 0)
      {
        ToastUtils.show("剩余抽奖次数不足");
        return;
      }
    }

    if(!this._btnDisable && this.interval == null)
    {
      Alert.alert('提示','是否消耗' + this.state.awardData.cost + '积分进行抽奖', [
          {text:'确定',onPress:()=>{
            this._submitChoujiang();
          }},
          {text:"取消", onPress:()=> {

          }}
        ])
    }
    else if(this.interval != null) {
      ToastUtils.show("正在抽奖，请稍后");
    }
  }

  _submitChoujiang() {
    if(this._getPoint() < this.getCost() )
    {
      ToastUtils.show("积分不足");
      return;
    }
    this._requestChoujiang();
  }

  zhuanpan(){
    if(this.interval != null){
      clearTimeout(this.interval);
      this.interval = null;
    }
    this._btnDisable = true;
    this.selectedItemCount = 0;
    this.setState({curBtnIndex:-1});
    this.interval = setInterval(() => {
      var tmpBtnIndex = this.state.curBtnIndex;
      tmpBtnIndex += 1;
      if(tmpBtnIndex > 7)
      {
        tmpBtnIndex = 0;
      }
      this.selectedItemCount += 1;

      this.setState({curBtnIndex:tmpBtnIndex});

      if(this.selectedItemCount > this.getNeedSelectCount())
      {
        this._requestPoint();
        //谢谢惠顾
        if(this.state.luckData.type === 5) {
          ToastUtils.show(this.state.luckData.name);
        }
        else {
          ToastUtils.show("获得：" + this.state.luckData.name + " * " + this.state.luckData.num);
        }
        clearTimeout(this.interval);
        this.interval = null;
        this._btnDisable = false;
      }
    }, 100);
  }

  //获取需要转多少格
  getNeedSelectCount(){
    var luckIndex = 0;
    if(this.state.luckData != null && this.state.luckData.award_id != undefined)
    {
      luckIndex = this.awardIdData[this.state.luckData.award_id];
    }
    luckIndex += 8 * 3;
    return luckIndex;
  }

  _requestChoujiang(){
    new JifenMallChoujiangAction().call(this, {});
  }

 _renderNoticeTxt(){
  console.log(this._listViewe)
   return(
     <View style={{flexDirection:"row", position:"absolute",
        backgroundColor:'#fff',
        height:SizeUtils.translateDesignHeightToCode(80),
        width:this._midBgHeight+SizeUtils.translateDesignWidthToCode(-40),
        left:(SizeUtils.getWindowSize().width - this._midBgHeight-SizeUtils.translateDesignWidthToCode(-40))/2,
        top:this._cellListTop - SizeUtils.translateDesignHeightToCode(40)+this._midBgHeight, alignItems:"center",}}>
        <Image style={{marginLeft:SizeUtils.translateDesignWidthToCode(20)}} source={require("../../../resource/images/jifenmall/mingdan.png")} />
     </View>
   )
 }

 _renderLuckerList(){
   return(
     <CommonDataListView style={{
        width:SizeUtils.getWindowSize().width,
         height:SizeUtils.getWindowSize().height}}
         ref={(ref) => {this._listViewe = ref}}
      //  ref={(ref) => {this._listView = ref}}
      //  onPressItem = {this._onPressItem.bind(this)}
       onRenderHeader={this._onRenderHeader.bind(this)}
       requestData = {this._requestData.bind(this)}
       isTR={true}
       onRenderItem = {this._onRenderItem.bind(this)}
       noEmpty = {true}
     />
   )
 }
 _onRenderItem(data, index) {
    const bgColor = index%2===0?'#f0f9ff':'#fff';
   return (
     <View style={{flexDirection:"row",width:this._midBgHeight+SizeUtils.translateDesignWidthToCode(-40),
        marginLeft:(SizeUtils.getWindowSize().width - this._midBgHeight-SizeUtils.translateDesignWidthToCode(-40))/2,
        backgroundColor:bgColor,
        alignItems: 'center',
        justifyContent: 'space-between', height:SizeUtils.translateDesignHeightToCode(80),
        }}>
       <Text style={{color:"#5a9ef3", paddingLeft:15, fontSize:SizeUtils.translateFontSizeToCode(26), textAlign:"left",
            width:(this._midBgHeight+SizeUtils.translateDesignWidthToCode(-40))/2, }}>{data.by_name}</Text>
       <Text style={{color:"#5a9ef3",paddingRight:15, fontSize:SizeUtils.translateFontSizeToCode(26), textAlign:"right",
            width:(this._midBgHeight+SizeUtils.translateDesignWidthToCode(-40))/2, }}>{data.name}*{data.num}</Text>
     </View>
   );
 }

 _requestData(page, listView) {
   new JifenMallGetLuckerListAction().call(listView, {page:page, page_size:10});
 }

 _dealEnterPage() {
   this.leavePanel();
 }

 _dealLeavePage() {
   this.leavePanel();
 }

 leavePanel(){
   this.setState({curBtnIndex:-1});
   this._btnDisable = false;
   clearTimeout(this.interval);
   this.interval = null;
   this.awardIdData = {};
 }

}
